#!/bin/bash
# master-init.sh - Master节点初始化脚本

source vars.sh

# 错误捕获
exec 2>>$LOG_FILE
set -e

trap 'handle_error "$BASH_COMMAND" "$?"' ERR

echo -e "${RED}>>> 1. 设置主机名${RESET}"
hostnamectl set-hostname $MASTER_NAME || handle_error "设置主机名失败" $?

echo -e "${RED}>>> 2. 配置hosts文件${RESET}"
for node in "${ALL_NODES[@]}"; do
    if ! grep -q "$node" /etc/hosts; then
        echo -e "${MAGENTA}-- 添加记录: $node${RESET}"
        echo "$node" >> /etc/hosts || handle_error "写入hosts文件失败" $?
    fi
done


echo -e "${RED}>>> 3. 关闭防火墙和SELinux${RESET}"
systemctl stop firewalld || handle_error "停止防火墙失败" $?
systemctl disable firewalld || handle_error "禁用防火墙失败" $?
setenforce 0 || handle_error "临时关闭SELinux失败" $?
sed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/selinux/config || handle_error "永久关闭SELinux失败" $?


echo -e "${RED}>>> 4. 禁用Swap${RESET}"
swapoff -a || handle_error "临时关闭Swap失败" $?
sed -i '/swap/s/^/#/' /etc/fstab || handle_error "永久关闭Swap失败" $?


echo -e "${RED}>>> 5. 内核参数配置${RESET}"
cat > /etc/sysctl.d/k8s.conf <<EOF || handle_error "创建内核配置文件失败" $?
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
net.ipv4.ip_forward = 1
EOF
sysctl --system || handle_error "应用内核参数失败" $?


echo -e "${RED}>>> 6. Docker版本检查与安装${RESET}"
TARGET_DOCKER_VERSION="20.10.24"
NEED_INSTALL_DOCKER=true

if command -v docker &> /dev/null; then
    CURRENT_DOCKER_VERSION=$(docker version --format '{{.Server.Version}}')
    if [[ "$CURRENT_DOCKER_VERSION" == "$TARGET_DOCKER_VERSION" ]]; then
        echo -e "${MAGENTA}-- 已安装目标版本Docker ($TARGET_DOCKER_VERSION)，跳过安装${RESET}"
        NEED_INSTALL_DOCKER=false
    else
        echo -e "${MAGENTA}-- 发现不兼容的Docker版本 ($CURRENT_DOCKER_VERSION)，正在卸载...${RESET}"
        yum remove -y docker \
            docker-client \
            docker-client-latest \
            docker-common \
            docker-latest \
            docker-latest-logrotate \
            docker-logrotate \
            docker-engine || handle_error "卸载Docker失败" $?
        rm -rf /var/lib/docker || handle_error "删除Docker残留文件失败" $?
    fi
fi

if $NEED_INSTALL_DOCKER; then
    echo -e "${MAGENTA}-- 开始安装Docker $TARGET_DOCKER_VERSION${RESET}"
    yum install -y wget || handle_error "安装wget失败" $?
    wget https://gitee.com/xy12306/Docker/releases/download/v1.7/install_docker.sh || handle_error "下载Docker安装脚本失败" $?
    chmod +x install_docker.sh && ./install_docker.sh || handle_error "执行Docker安装失败" $?
fi

echo -e "${MAGENTA}-- 配置Docker${RESET}"
cat > /etc/docker/daemon.json <<EOF || handle_error "创建Docker配置失败" $?
{
    "registry-mirrors": [
        "https://docker.xuanyuan.me",
        "https://docker.1ms.run",
        "https://docker.m.daocloud.io",
        "https://atomhub.openatom.cn"
    ],
    "exec-opts": ["native.cgroupdriver=systemd"]
}
EOF
systemctl daemon-reload && systemctl restart docker || handle_error "重启Docker失败" $?

echo -e "${RED}>>> 7. 安装cri-dockerd${RESET}"
wget https://github.com/Mirantis/cri-dockerd/releases/download/v0.3.2/cri-dockerd-0.3.2-3.el7.x86_64.rpm || handle_error "下载cri-dockerd失败" $? "7"
rpm -ivh cri-dockerd-0.3.2-3.el7.x86_64.rpm || handle_error "安装cri-dockerd失败" $? "7"
sed -i '/ExecStart/s/$/ --pod-infra-container-image=registry.aliyuncs.com\/google_containers\/pause:3.9/' \
    /usr/lib/systemd/system/cri-docker.service || handle_error "修改cri-dockerd配置失败" $? "7"
systemctl daemon-reload && systemctl enable --now cri-docker || handle_error "启动cri-dockerd失败" $? "7"


echo -e "${RED}>>> 8. 添加K8s源${RESET}"
cat > /etc/yum.repos.d/kubernetes.repo <<EOF || handle_error "创建K8s源失败" $?
[kubernetes]
name=Kubernetes
baseurl=https://mirrors.aliyun.com/kubernetes/yum/repos/kubernetes-el7-x86_64/
enabled=1
gpgcheck=1
repo_gpgcheck=1
gpgkey=https://mirrors.aliyun.com/kubernetes/yum/doc/yum-key.gpg \
       https://mirrors.aliyun.com/kubernetes/yum/doc/rpm-package-key.gpg
EOF


echo -e "${RED}>>> 9. 安装k8s组件${RESET}"
yum install -y kubelet-1.28.0 kubeadm-1.28.0 kubectl-1.28.0 || handle_error "安装K8s组件失败" $?
systemctl enable kubelet || handle_error "启用kubelet失败" $?


echo -e "${RED}>>> 10. 初始化Master${RESET}"
kubeadm init \
  --apiserver-advertise-address=$MASTER_IP \
  --image-repository registry.aliyuncs.com/google_containers \
  --kubernetes-version v1.28.0 \
  --service-cidr=10.96.0.0/12 \
  --pod-network-cidr=10.244.0.0/16 \
  --cri-socket=unix:///var/run/cri-dockerd.sock || handle_error "Master初始化失败" $?


echo -e "${MAGENTA}-- 配置kubectl${RESET}"
mkdir -p $HOME/.kube || handle_error "创建.kube目录失败" $?
cp /etc/kubernetes/admin.conf $HOME/.kube/config || handle_error "复制配置文件失败" $?
chown $(id -u):$(id -g) $HOME/.kube/config || handle_error "修改文件权限失败" $?



echo -e "${RED}>>> 12. 安装Calico${RESET}"
CALICO_FAILED=0
if ! wget https://raw.githubusercontent.com/projectcalico/calico/v3.26.1/manifests/calico.yaml; then
    echo -e "${YELLOW}⚠️ Calico下载失败，请稍后手动执行："
    echo -e "wget https://raw.githubusercontent.com/projectcalico/calico/v3.26.1/manifests/calico.yaml${RESET}"
    CALICO_FAILED=1
else
    if ! kubectl apply -f calico.yaml; then
        echo -e "${YELLOW}⚠️ Calico应用失败，请稍后手动执行："
        echo -e "kubectl apply -f calico.yaml${RESET}"
        CALICO_FAILED=1
    fi
fi

# 无论Calico是否成功都显示状态检查命令
if [ $CALICO_FAILED -eq 0 ]; then
    echo -e "${YELLOW}\n✅ Calico已应用，可通过以下命令查询部署状态："
else
    echo -e "${YELLOW}\n⚠️ Calico未完全安装，请手动执行上述命令后检查状态："
fi
echo -e "kubectl get pods -n kube-system -w"
echo -e "或使用以下命令检查Calico Pod的状态："
echo -e "kubectl get pods -n kube-system | grep calico${RESET}"

# 始终生成并显示加入命令
echo -e "\n${YELLOW}>>> Master节点初始化完成！请使用以下命令加入节点：${RESET}"
if JOIN_CMD=$(kubeadm token create --print-join-command 2>/dev/null); then
    echo -e "${YELLOW}$JOIN_CMD --cri-socket=unix:///var/run/cri-dockerd.sock${RESET}"
else
    echo -e "${RED}生成join命令失败，请手动创建token："
    echo -e "kubeadm token create --print-join-command"
    echo -e "并在命令末尾追加：--cri-socket=unix:///var/run/cri-dockerd.sock${RESET}"
fi
echo -e "${YELLOW}⚠️ 发现错误请检查日志文件: $LOG_FILE ${RESET}"